package com.tuanzi.blog.back.controller;


import com.tuanzi.blog.back.bean.User;
import com.tuanzi.blog.back.service.UserService;
import com.tuanzi.blog.base.bean.ResultVo;
import com.tuanzi.blog.base.exception.BlogException;
import com.tuanzi.blog.base.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {


    @Autowired
    private UserService userservice;

    /**
     * 通过自定义异常来定义系统中出现异常情况
     * 使用枚举来实现用户操作失败的定义情况
     * 使用ResultVo给客户端返回具体操作的结果信息
     * @param user
     * @param code
     * @param session
     */
    @RequestMapping(value = "/back/user/login")
    @ResponseBody
    public ResultVo login(User user, String code, HttpSession session){

        ResultVo resultVo = new ResultVo();

        //从session中获取正确的验证码
        String rightCode = (String) session.getAttribute("code");

        try{
            user = userservice.login(user,code,rightCode);
            resultVo.setOk(true);
            //把登录的用户放到session中
            session.setAttribute("user",user);
        }catch (BlogException e){
            resultVo.setOk(false);
            resultVo.setMess(e.getMessage());
        }
        return resultVo;
    }

    /**
     * 用户登录成功后跳转到后台
     */
    @RequestMapping(value = "/workbench/index")
    public String toIndex(){

        return "workbench/index";

    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/user/loginOut")
    public String loginOut(HttpSession session){
        //清除session中的用户对象
        session.removeAttribute("user");
        //重定向到登录页面
        return "redirect:/login.jsp";
    }

    /**
     * 异步校验用户输入的原始密码是正确
     */
    @RequestMapping(value = "/user/verifyOldPwd")
    @ResponseBody
    public ResultVo verifyOldPwd(String oldPwd,HttpSession session){
        ResultVo resultVo = new ResultVo();
        try{
            //获取当前登录用户
            User user = (User) session.getAttribute("user");
            userservice.verifyOldPwd(oldPwd,user);
            resultVo.setOk(true);
        }catch (BlogException e){
            resultVo.setOk(false);
            resultVo.setMess(e.getMessage());
        }
        return resultVo;

    }

    /**
     * 异步修改用户信息
     */
    @RequestMapping(value = "/user/updateUser")
    @ResponseBody
    public ResultVo updateUser(User user){
        ResultVo resultVo = new ResultVo();
        try{
            userservice.updateUser(user);
            resultVo.setOk(true);
            resultVo.setMess("修改用户信息成功！！！");
        }catch (BlogException e){
            resultVo.setOk(false);
            resultVo.setMess(e.getMessage());
        }
        return resultVo;

    }

}
